$(function(){

    //获取url参数
	function GetQueryString(name){
		var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if(r!=null)return unescape(r[2]); return null;
    }

    //弹出遮罩层
    addStudentView=function(){
        $("#student_id").val("");
        $("#student_name").val("");
        $("#student_phone").val("");
        $("#modal-add-student").modal("show");
    }

    //添加学生
    addStudentSubmit=function(table,myAction){
        student_id=$("#student_id").val();
        name=$("#student_name").val();
        gender=$("#student_gender").val();
        phone=$("#student_phone").val();
        grade=$("#student_grade").val();
        major=$("#student_major").val();
        classs=$("#class").val();

        studentList=new Array();
        student=new Object();
        student.student_id=student_id;
        student.name=name;
        student.gender=gender;
        student.phone=phone;
        student.grade=grade;
        student.major=major;
        student.class=classs;
        studentList[0]=student;

        studentJSON=JSON.stringify(studentList);
        //alert(studentJSON);
        $.post("/php/student-information-register.php",{action:1,data:studentJSON},function(result){
            resultObj=JSON.parse(result);
            alert(result);
            switch(resultObj.code){
                case '2001':
                    layer.msg(resultObj.message,{time:3000,btn:['确定'],icon:1},
                    function(){
                        location.replace(location.href);
                    });
                    break;
                case '2003':
                    layer.msg(resultObj.message);
                    serverValidate(JSON.parse(resultObj.error),1);
                    break;
                case '2004':
                    layer.msg(resultObj.message);
                    break;
                default:layer.msg(resultObj.message);break;
            }
        });

    }

    //编辑学生信息界面
    editStudentInfoView=function(table){
        $("#update_student_id").val($(table).parents("tr").find(".student_id").html());
        $("#update_student_name").val($(table).parents("tr").find(".name").html());
        $("#update_gender_select").val($(table).parents("tr").find(".gender_id").html());
        $("#update_student_phone").val($(table).parents("tr").find(".phone_number").html());
        $("#update_grade_select").val($(table).parents("tr").find(".grade").html());
        $("#update_major_select").val($(table).parents("tr").find(".major_id").html());
        $("#update_class").val($(table).parents("tr").find(".class").html());
        $("#modal-update-student").modal("show");
    }
    //修改信息
    editStudentInfo=function(){
        student_id=$("#update_student_id").val();
        name=$("#update_student_name").val();
        gender=$("#update_gender_select").val();
        phone=$("#update_student_phone").val();
        grade=$("#update_grade_select").val();
        major=$("#update_major_select").val();
        classs=$("#update_class").val();

        studentList=new Array();
        student=new Object();
        student.student_id=student_id;
        student.name=name;
        student.gender=gender;
        student.phone=phone;
        student.grade=grade;
        student.major=major;
        student.class=classs;
        studentList[0]=student;

        studentJSON=JSON.stringify(studentList);

        $.post("/php/student-information-register.php",{action:2,data:studentJSON},function(result){
            //alert(result);
            resultObj=JSON.parse(result);
            switch(resultObj.code){
                case '2001':
                    layer.msg(resultObj.message,{time:3000,btn:['确定'],icon:1},
                    function(){
                        location.replace(location.href);
                    });
                    break;
                case '2003':
                    layer.msg(resultObj.message);
                    serverValidate(JSON.parse(resultObj.error),2)
                    break;
                case '2004':
                    layer.msg(resultObj.message);
                    break;
                default:layer.msg(resultObj.message);break;
            }
        });
    }

    //服务器验证信息
    function serverValidate(error,action){
        id_array=new Array();
        add_id=[
            {'name':'student_id','id':'#student_id'},
            {'name':'name','id':'#student_name'},
            {'name':'phone','id':'#student_phone'},
            {'name':'class','id':'#class'}
        ];
        update_id=[
            {'name':'student_id','id':'#update_student_id'},
            {'name':'name','id':'#update_student_name'},
            {'name':'phone','id':'#update_student_phone'},
            {'name':'class','id':'#update_class'}
        ];
        switch(parseInt(action)){
            case 1:id_array=add_id;break;
            case 2:id_array=update_id;break;
            default:break;
        }
        for(i=0;i<error.length;i++){
            for(j=0;j<error[i].length;j++){
                //alert(error[i].length+"-"+id_array.length);
                for(c=0;c<id_array.length;c++){
                    //alert(id_array[c].name+"="+id_array[c].id+"="+error[i][j]);
                    if(id_array[c].name==error[i][j]){
                        $(id_array[c].id).addClass('error');
                        $(id_array[c].id+"-error").show();
                    }
                }
            }
        }
    }

    //移除学生
    removeStudent=function(student_id){
        studentList=new Array();
        student=new Object();
        student.student_id=student_id;
        studentList[0]=student;
        studentJSON=JSON.stringify(studentList);
        layer.confirm('确定删除？',{btn:['确定','取消']},function(){
            $.post("/php/student-information-register.php",{action:3,data:studentJSON},function(result){
                resultObj=JSON.parse(result);
                switch(resultObj.code){
                    case '2001':
                        layer.msg(resultObj.message,{btn:['确定'],icon:1},function(){
                            location.replace(location.href);
                        })
                        break;
                    case '2002':layer.msg(resultObj.message);break;
                    case '2003':layer.msg(resultObj.message);break;
                    case '2004':
                        layer.msg(resultObj.message);
                        break;
                    default:break;
                }
            });
        });
    }

    //移除选中学生
    removeStudentChecked=function(){
        studentList=new Array();
        $(":checkbox[name='chekbox_student']:checked").each(function(index,e){
            student=new Object();
            student.student_id=$(this).val();
            studentList[index]=student;
        });

        if(studentList.length>0){
            studentJSON=JSON.stringify(studentList);
            layer.confirm('确定删除？',{btn:['确定','取消']},function(){
                $.post("/php/student-information-register.php",{action:3,data:studentJSON},function(result){
                    resultObj=JSON.parse(result);
                    switch(resultObj.code){
                        case '2001':
                            layer.msg(resultObj.message,{btn:['确定'],icon:1},function(){
                                location.replace(location.href);
                            })
                            break;
                        case '2002':layer.msg(resultObj.message);break;
                        case '2003':layer.msg(resultObj.message);break;
                        case '2004':
                            layer.msg(resultObj.message);
                            break;
                        default:layer.msg(resultObj.message);break;
                    }
                });
            });
        }else{
            layer.msg("未选中任何学生");
        }
    }

    //跳页
    $("select").change(function(){
        var grade=GetQueryString('grade');
        grade=(grade==null?0:grade);

        var major=GetQueryString('major');
        major=(major==null?0:major);

        var classs=GetQueryString('class');
        classs=(classs==null?0:classs);

        var search=GetQueryString('search');
        search=search==null?'':search;


		var id=$(this).attr("id");
        switch(id){
			case 'student_page':
                url="./student-information-register.php?grade="+grade+"&major="+major
                +"&class="+classs+"&page="+$(this).val()+"&search="+search;
				window.location.href=url;
			break;
			default:break;
		}
	});

    //恢复默认样式
	$("input").click(function(){
		$(this).removeClass('error');
		var val=$(this).attr("id");
		var label_id="#"+val+"-error";
		$(label_id).hide();
	});

    //上传控件初始化
    var uploader;
    initWebuploader();
    function initWebuploader(){
        uploader = WebUploader.create({
            // swf文件路径 BASE_URL + 
            swf: 'http://127.0.0.1:8800/lib/webuploader/0.1.5/Uploader.swf',

            // 文件接收服务端。
            //server: 'http://127.0.0.1:8800/lib/webuploader/0.1.5/server/fileupload.php',
            server: 'http://127.0.0.1:8800/file-upload.php',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker',
            fileNumLimit:1,
            fileSingleSizeLimit: 10*1024*1024,
            // 只允许选择excel表格文件。
            accept:{
                title :'Files',
                extensions:'xls,xlsx',
                mimeTypes:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        });
    }
    
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {

    });
    uploader.on("error",function (type){
        if(type == "Q_TYPE_DENIED") {
            layer.msg("请上传xls、xlsx格式文件");
        }else if(type == "F_DUPLICATE"){
              //win.alert("系统提示","请不要重复选择文件！");
        }else if(type == "Q_EXCEED_SIZE_LIMIT"){
              //alert('文件大小');
        }
     });

    //上传成功
    uploader.on( 'uploadSuccess', function( file,dataObj) {
        //data=JSON.stringify(json);
        //data=data.replace(/[\\]/g, '');
        //dataObj=json.data;
        //dataObj=JSON.parse(data);
        alert(JSON.stringify(dataObj)+"'");
        
        //dataObj=json.data;
        //dataObj=JSON.parse(json);
        
        switch(dataObj.code){
            //导入成功
            case '2001':
            layer.msg(dataObj.message,{icon:1,time:3000,btn:['确定']},function(){
                location.replace(location.href);
            })
            break;
            //学号重复
            case '2002':
            layer.msg(dataObj.message);
            break;
            //输入不符合要求
            case '2003':
            layer.msg(dataObj.message);
            break;
            //导入失败
            case '2004':
            layer.msg(dataObj.message);
            break;
            default:layer.msg(dataObj.message);break;
        }
        //layer.msg("上传成功");
    });

    uploader.on( 'uploadError', function( file ) {
        layer.msg("上传失败");
    });

    //不管上传成功或失败都会执行
    uploader.on( 'uploadComplete', function( file ) {
        uploader.reset();
        //uploader.destroy();
        //initWebuploader();
    });
    
    // 注册全部按钮事件
    $("#ctlBtn").click(function(){
        uploader.upload();
    });
});
